package com.kanshu.ksgb.fastread.doudou.module.bookcity.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.event.AdRefreshEvent;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.PageRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.common.view.tablayout.SlidingTabLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.event.ScrollEvent;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.adapter.SelectedBottomAdapter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.adapter.SelectedTopAdapter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.ISelectedView;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.view.AdSelectedHeaderLayout;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by wcy on 18/5/14.
 */

public class AdSelectedFragment extends BaseFragment implements ISelectedView, BookCityCallListener {

    @BindView(R.id.recyler_view_bottom)
    RecyclerView mRecylerViewBottom;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    Unbinder mUnbinder;
    PageRequestParams mRequestParams;
    List<SelectedBean> mSelectedBeans = new ArrayList<>();
    List<BookInfo> mBookInfos = new ArrayList<>();
    SelectedBottomAdapter mAdapter;
    SelectedTopAdapter mTopAdapter;
    BookCityPresenter mPresenter;
    AdSelectedHeaderLayout mHeaderLayout;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    boolean mSwitch;
    int mTotalPage;
    @BindView(R.id.scroll_to_top)
    ImageView mScrollToTop;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mPresenter = new BookCityPresenter(lifeCyclerSubject);
        mAdapter = new SelectedBottomAdapter(getActivity(), mBookInfos);
        mPresenter.setSelectedView(this);
        mRequestParams = new PageRequestParams();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_selected_layout, null);
        mUnbinder = ButterKnife.bind(this, view);
        View headerView = inflater.inflate(R.layout.item_selected_header_layout, null);
        RecyclerView recyclerView = (RecyclerView) headerView.findViewById(R.id.recyler_view_top);
        View footerView = inflater.inflate(R.layout.item_selected_bottom_header_layout, null);
        mTopAdapter = new SelectedTopAdapter(getActivity(), mSelectedBeans, Constants.BookCityTabType.TYPE_SELECTED);
        mHeaderLayout = new AdSelectedHeaderLayout(getActivity(), Constants.BookCityTabType.TYPE_SELECTED);
        mTopAdapter.addHeaderView(mHeaderLayout);
        mTopAdapter.addFooterView(footerView);
        mAdapter.addHeaderView(headerView);
        footerView.findViewById(R.id.change).setOnClickListener(v -> {
            mRequestParams.page++;
            mSwitch = true;
            if (mRequestParams.page > mTotalPage) {
                mRequestParams.page = 1;
            }
            mPresenter.getBottomContents(mRequestParams);
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN11_WANRENZHIXUAN);
        });
        mAdapter.setRequestDataListener(() -> mPresenter.getBottomContents(mRequestParams));
        RecyclerViewHelper.initRecyclerViewV(getActivity(), recyclerView, mTopAdapter);
        RecyclerViewHelper.initRecyclerViewV(getActivity(), mRecylerViewBottom, mAdapter);
        RecyclerViewHelper.closeDefaultAnimator(mRecylerViewBottom);
        RecyclerViewHelper.closeDefaultAnimator(recyclerView);
        SwipeRefreshHelper.init(mSwipeRefresh, () -> {
            mHeaderLayout.refresh();
            mPresenter.getSelectedInfos(mRequestParams);
            mTopAdapter.reset();
        });
        mAdapter.setOnItemClickListener((view1, position) -> {
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN11_WANRENZHIXUAN);
            position = position - mAdapter.getHeaderViewsCount();
            ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", mBookInfos.get(position).book_id);
        });
        mEmptyLayout.setRetryListener(new EmptyLayout.OnRetryListener() {
            @Override
            public void onRetry() {
                mHeaderLayout.refresh();
                mPresenter.getSelectedInfos(mRequestParams);
            }
        });
        AdSelectedFragment.scrollToTop(mRecylerViewBottom, mScrollToTop,
                true, ((AdBookCityFragment) getParentFragment()).getTop(),
                ((AdBookCityFragment) getParentFragment()).getTabLayout(),
                ((AdBookCityFragment) getParentFragment()).getSearch(),
                ((AdBookCityFragment) getParentFragment()).getTopMask(), Constants.BookCityTabType.TYPE_SELECTED);
        return view;
    }

    @Override
    protected void updateViews() {
        super.updateViews();
        mHeaderLayout.refresh();
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
        mPresenter.getSelectedInfos(mRequestParams);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
        EventBus.getDefault().unregister(this);
        if (mSwipeRefresh != null) {
            mSwipeRefresh.finishRefreshing();
        }
        mTopAdapter.clear();
        mPresenter.detachView();
    }


    @Override
    public void showLoading(String s) {
    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    public void showContent(BaseResult<List<SelectedBean>> result) {
        DisplayUtils.visible(mRecylerViewBottom);
        List<SelectedBean> data = result.result.data;
        if (!Utils.isEmptyList(data) && data.size() >= 4) {
            List<SelectedBean> data1 = data.subList(0, data.size() / 2);
            //List<SelectedBean> data2 = data.subList(data.size() / 2, data.size());
            List<SelectedBean> data2 = new ArrayList<>();
            int start = data.size() / 2;
            for (int i = data.size() / 2; i < data.size(); i++) {
                data2.add(data.get(i));
            }
            int itemCount = data2.size();
            mTopAdapter.setDatas(data1);
            AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
                @Override
                public void run() {
                    List<SelectedBean> datas = mTopAdapter.getDatas();
                    datas.addAll(data2);
                    mTopAdapter.notifyItemRangeChanged(start, itemCount);
                }
            }, 1500, TimeUnit.MILLISECONDS);
        } else {
            mTopAdapter.setDatas(result.result.data);
        }
        AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                // 请求万人之选的数据
                mPresenter.getBottomContents(mRequestParams);
            }
        }, 2000, TimeUnit.MILLISECONDS);
        AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                // 请求万人之选的数据
                mPresenter.getBottomContents(mRequestParams);
            }
        }, 2000, TimeUnit.MILLISECONDS);
        dismissLoading();
    }

    @Override
    public void showError(int errCode, String errDesc) {
        Log.d("wcy", "showError errdesc:" + errDesc);
        dismissLoading();
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, null);
        if (!NetUtils.isNetworkAvailable(getActivity())) {
            int status = EmptyLayout.STATUS_NO_NET;
            if (mEmptyLayout != null) {
                mEmptyLayout.setEmptyStatus(status);
            }
            DisplayUtils.gone(mRecylerViewBottom);
        }
        //showEmptyByCode(errCode, mEmptyLayout);
    }

    @Override
    public void showBottomContent(BaseResult<List<SelectedBean>> result) {
        DisplayUtils.visible(mRecylerViewBottom);
        if (Utils.isEmptyList(result.result.data)) {
            return;
        }
        if (mRequestParams.page == 1 || mSwitch) {
            mSwitch = false;
            if (Utils.isEmptyList(result.result.data) && mBookInfos.size() <= 0) {
                SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
                return;
            }
            mBookInfos.clear();
            mAdapter.setIsNoMoreData(false);
        }
        mBookInfos.addAll(result.result.data.get(0).list);
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
        mTotalPage = result.result.data.get(0).page_info.total_page;
        if (result.result.data.get(0).page_info != null) {
            if (mRequestParams.page >= result.result.data.get(0).page_info.total_page) {
                mAdapter.noMoreData();
            } else {
                mRequestParams.page++;
            }
        } else {
            mAdapter.noMoreData();
        }
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void showBottomError(int code, String desc) {
        Log.d("wcy", "showBottomError errdesc:" + desc);
        if (!NetUtils.isNetworkAvailable(getActivity())) {
            int status = EmptyLayout.STATUS_NO_NET;
            if (mEmptyLayout != null) {
                mEmptyLayout.setEmptyStatus(status);
                DisplayUtils.gone(mRecylerViewBottom);
            }
        }
    }

    /**
     * @param recylerView
     * @param scrollToTop
     */
    public static void scrollToTop(final RecyclerView recylerView, View scrollToTop, boolean hasHeader, View top, SlidingTabLayout tabLayout, ImageView search, ImageView topMask, int type) {
        scrollToTop.setOnClickListener(v -> {
            if (type == Constants.BookCityTabType.TYPE_SELECTED)
                AdPresenter.pvuvStatics(R.string.SCTOP_BUTTON);
            recylerView.scrollToPosition(0);
            scrollToTop.setVisibility(View.INVISIBLE);
            top.setBackgroundColor(Color.TRANSPARENT);
            topMask.setVisibility(View.VISIBLE);
            search.setImageResource(R.mipmap.ic_search_white);
            tabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_NONE);
            tabLayout.setIndicatorColor(recylerView.getContext().getResources().getColor(R.color.white));
            tabLayout.setTextSelectColor(Color.WHITE);
            tabLayout.setTextUnselectColor(recylerView.getContext().getResources().getColor(R.color.book_city_tab_unselect_color));
        });
        recylerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int mHeaderHeight = -1;

            public int getScollYDistance(RecyclerView recyclerView) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                if (firstVisiableChildView == null) {
                    return mHeaderHeight;
                }
                int itemHeight = firstVisiableChildView.getHeight();
                Log.d("wcy", "pos:" + position);
                if (position == 0 && hasHeader) {
                    mHeaderHeight = (position) * itemHeight - firstVisiableChildView.getTop();
                    return (position) * itemHeight - firstVisiableChildView.getTop();
                } else {
                    return mHeaderHeight + (position) * itemHeight - firstVisiableChildView.getTop();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 判断是否滚动超过一屏
                if (getScollYDistance(recyclerView) < DisplayUtils.getScreenHeight(recyclerView.getContext())) {
                    scrollToTop.setVisibility(View.INVISIBLE);
                } else {
                    scrollToTop.setVisibility(View.VISIBLE);
                }
                if (getScollYDistance(recyclerView) > 0) {
                    top.setBackgroundColor(Color.WHITE);
                    topMask.setVisibility(View.GONE);
                    tabLayout.setIndicatorColor(recyclerView.getContext().getResources().getColor(R.color.theme));
                    tabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_WHEN_SELECT);
                    search.setImageResource(R.mipmap.ic_search);
                    tabLayout.setTextSelectColor(Color.parseColor("#333333"));
                    tabLayout.setTextUnselectColor(Color.parseColor("#999999"));
                } else {
                    topMask.setVisibility(View.VISIBLE);
                    top.setBackgroundColor(Color.TRANSPARENT);
                    search.setImageResource(R.mipmap.ic_search_white);
                    tabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_NONE);
                    tabLayout.setIndicatorColor(recyclerView.getContext().getResources().getColor(R.color.white));
                    tabLayout.setTextSelectColor(Color.WHITE);
                    tabLayout.setTextUnselectColor(recyclerView.getContext().getResources().getColor(R.color.book_city_tab_unselect_color));
                }
                Log.d("wcy", "scrollY:" + recyclerView.getScrollY());
                Log.d("wcy", "dy:" + dy + "getScollYDistance:" + getScollYDistance(recyclerView));
            }
        });
    }

    @Override
    public int getScrollDistance() {
        return Utils.getRecyclerScrollDistance(mRecylerViewBottom);
    }


    public static void showEmptyByCode(int code, EmptyLayout emptyLayout) {
        int status = EmptyLayout.STATUS_NO_NET;
        if (code == Constants.ErrCode.NoData) {
            status = EmptyLayout.STATUS_NO_DATA;
        }
        if (emptyLayout != null) {
            emptyLayout.setEmptyStatus(status);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleScrollEvent(ScrollEvent event) {
        if (event.type == Constants.BookCityTabType.TYPE_SELECTED
                && mRecylerViewBottom != null) {
            mRecylerViewBottom.scrollToPosition(0);
            ((AdBookCityFragment) getParentFragment()).getTop().setBackgroundColor(Color.TRANSPARENT);
            ((AdBookCityFragment) getParentFragment()).getSearch().setImageResource(R.mipmap.ic_search_white);
            SlidingTabLayout tabLayout = ((AdBookCityFragment) getParentFragment()).getTabLayout();
            tabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_NONE);
            tabLayout.setIndicatorColor(getContext().getResources().getColor(R.color.white));
            tabLayout.setTextSelectColor(Color.WHITE);
            tabLayout.setTextUnselectColor(getContext().getResources().getColor(R.color.book_city_tab_unselect_color));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleAdRefreshEvent(AdRefreshEvent event) {
        if (mTopAdapter != null) {
            mTopAdapter.reset();
        }
    }
}
